package com.test.mvcframework.pojo.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;


/**
 * 封装handler方法相关的信息
 *
 * @author felix
 */
public class MethodHandler implements Handler {
    private Object target;

    private Method method;

    private Map<String, Integer> paramIndexMapping;

    public MethodHandler(Object target, Method method, Map<String, Integer> paramIndexMapping) {
        this.target = target;
        this.method = method;
        this.paramIndexMapping = paramIndexMapping;
    }

    @Override
    public Object handle(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Object[] args = new Object[paramIndexMapping.size()];
        for (Map.Entry<String, Integer> entry : paramIndexMapping.entrySet()) {
            String key = entry.getKey();
            Object value = null;
            if (HttpServletRequest.class.getName().equals(key)) {
                value = request;
            } else if (HttpServletResponse.class.getName().equals(key)) {
                value = response;
            } else {
                value = request.getParameter(key);
            }
            args[entry.getValue()] = value;
        }
        return method.invoke(target, args);
    }

    public Object getTarget() {
        return target;
    }

    public Method getMethod() {
        return method;
    }

    public Map<String, Integer> getParamIndexMapping() {
        return paramIndexMapping;
    }
}
